//
//  BKBaseWebViewController.swift
//  BaoKeSwift
//
//  Created by geek-duan on 2017/10/11.
//  Copyright © 2017年 geek-duan. All rights reserved.
//

import UIKit
import WebKit
import JavaScriptCore


class BaseWebViewController: UIViewController {
    
    // MARK: - 公开属性或方法
    /// - webView懒加载
    lazy var webView: WKWebView = {
        
        let webView = WKWebView.init(frame: CGRect(), configuration: self.configuration)
        webView.backgroundColor = UIColor.backgroundColor
        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        return webView
    }()

    /// - WebViewConfiguration懒加载
    lazy var configuration: WKWebViewConfiguration = {
        
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        configuration.userContentController = userContentController
        let preference = WKPreferences()
        preference.javaScriptCanOpenWindowsAutomatically = true
        configuration.preferences = preference
        configuration.selectionGranularity = .character
        return configuration
    }()
    
    /// - progressView懒加载
    lazy var progressView: UIProgressView = {
        
        let progressView = UIProgressView.init(progressViewStyle: .default)
        progressView.trackTintColor = UIColor.rgb(r: 240.0, g: 240.0, b: 240.0)
        progressView.progressTintColor = UIColor.green
        return progressView
    }()
    
    // MARK: - 加载请求页面数据
    func loadWebURLSring(urlStr: String) {
        guard let url = URL.init(string: urlStr) else {
            return
        }
        let request = URLRequest.init(url: url)
        webView.load(request)
    }
    
    func loadWebURL(Url: URL) {
        let request = URLRequest.init(url: Url)
        webView.load(request)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(self.webView)
        view.addSubview(self.progressView)
        setUI()
    }
    
    private func setUI() {
        webView.snp.makeConstraints { (make) in
            make.left.top.right.bottom.equalToSuperview()
        }
        progressView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(3)
        }
    }
    
    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
}

// MARK: -  KVO监听进度条
extension BaseWebViewController {

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if (keyPath == "estimatedProgress") {
            progressView.alpha = 1.0
            let animated = (webView.estimatedProgress > Double(progressView.progress))
            progressView.setProgress(Float(webView.estimatedProgress), animated: animated)
            
            if webView.estimatedProgress >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveEaseOut, animations: {
                    self.progressView.alpha = 1.0
                }, completion: { (finished) in
                    self.progressView.setProgress(0.0, animated: false)
                })
            }
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
}

// MARK: - WKNavigationDelegate代理方法
extension BaseWebViewController: WKNavigationDelegate {
    // MARK: - 页面开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        progressView.isHidden = false
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        progressView.isHidden = true
    }
}

// MARK: - WKUIDelegate代理方法
extension BaseWebViewController: WKUIDelegate {
    // MARK: - 获取js 里面的提示
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {}
}

extension BaseWebViewController: WKScriptMessageHandler {
    // MARK: - 拦截执行网页中的JS方法
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //服务器固定格式写法 window.webkit.messageHandlers.名字.postMessage(内容);
        //客户端写法 message.name isEqualToString:@"名字"
    }
}
